package com.pzl.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * zl.peng 2016-02-22 20:52:57
 */
public class ObScrollView extends ScrollView {
    private static final String TAG = "ObScrollView";
    private ObAdapter mObAdapter = null;
    private boolean mIsTouchMoving = false;
    /**
     * onFling状态下，到顶到底防止回调多次
     */
    private boolean mOnlyOnce = false;

    public ObScrollView(Context context) {
        super(context);
    }

    public ObScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ObScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (mObAdapter == null) return;
        if (getScrollY() + getHeight() >= computeVerticalScrollRange()) {
            if (mOnlyOnce) {
                mObAdapter.onScrollBottom();
                mOnlyOnce = false;
            } else if (mIsTouchMoving) {
                mObAdapter.onScrollBottom();
            }
        } else if (getScrollY() == 0) {
            if (mOnlyOnce) {
                mObAdapter.onScrollTop();
                mOnlyOnce = false;
            } else if (mIsTouchMoving) {
                mObAdapter.onScrollTop();
            }
        } else {//move or fling
            if (!mIsTouchMoving) {
                mOnlyOnce = true;
            }
        }
    }


    public void setObAdapter(ObAdapter obAdapter) {
        this.mObAdapter = obAdapter;
    }

    public static interface IScrollListener {
        void onScrollBottom();// 到底

        void onScrollTop();//到顶
    }

    public static class ObAdapter implements IScrollListener {
        @Override
        public void onScrollBottom() {

        }

        @Override
        public void onScrollTop() {

        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mIsTouchMoving = false;
                break;
            case MotionEvent.ACTION_UP:
                mIsTouchMoving = false;
                break;
            case MotionEvent.ACTION_MOVE:
                mIsTouchMoving = true;
                break;
        }
        return super.onTouchEvent(ev);
    }
}
